import { _decorator, Component, Node, AudioSource, AudioClip, resources, director, tween, Vec3, find, assetManager, Label, ProgressBar, v3, MotionStreak, UIOpacity, Tween, log, Sprite, color, ParticleSystem2D, Vec2, UITransform, EventTouch, Button, Material, instantiate, Prefab } from 'cc';
import { weixinapi } from './weixinAIP';
import { SJTS } from '../../../jinruchangjing/SJTS';
import { CZdingshiqiTS } from './CZdingshiqiTS';
import TaskProxy from 'db://assets/3rd/Guyu/Scripts/[业务]/广告任务/Controller/TaskProxy';
import { CommonUI } from 'db://assets/3rd/Guyu/Scripts/[框架]/通用UI/CommonUI';



const { ccclass, property } = _decorator;

@ccclass('tongyongTS')
export class tongyongTS extends Component {
    @property(Node) TSnode: Node = null;

    yinpin: AudioSource


    bundle

    readonly banner最长停留实践 = 5



    onLoad() {
        this.yinpin = this.node.getComponent(AudioSource)

        this.bundle = assetManager.getBundle('fb')
        if (!this.bundle) {
            assetManager.loadBundle('fb', (err, a) => {
                this.bundle = assetManager.getBundle('fb')
            })
        }

    }


    protected start(): void {
        this.g关闭banner()



    }
    //声音

    bofangshenyin(a: Number, daxiao?: number) {
        //使用中：
        let wz = ''
        switch (a) {
            case 2: wz = 'dongtaijiazai/yy/jinru'; break;       //进入
            case 6: wz = 'dongtaijiazai/yy/dingdeng'; break;    //叮蹬
            case 9: wz = 'dongtaijiazai/yy/dinglinglianxu'; break; //连续叮铃
            case 10: wz = 'dongtaijiazai/yy/feichu'; break;     //飞出
            case 17: wz = 'dongtaijiazai/yy/zhua'; break;    //抓
            case 18: wz = 'dongtaijiazai/yy/shibaichang'; break;    //失败2
            case 19: wz = 'dongtaijiazai/yy/guanmeng'; break;    //关门
            case 20: wz = 'dongtaijiazai/yy/chudong'; break;    //出动
            case 21: wz = 'dongtaijiazai/yy/xintiao'; break;    //心跳
            case 22: wz = 'dongtaijiazai/yy/luodidong'; break;    //落地东
            case 23: wz = 'dongtaijiazai/yy/diaoluozhong'; break;    //掉落中
            case 25: wz = 'dongtaijiazai/yy/bangzi1'; break;    //棒子1
            case 26: wz = 'dongtaijiazai/yy/bangzi2'; break;    //棒子2
            case 27: wz = 'dongtaijiazai/yy/bingdong'; break;    //冰冻


            case 3: wz = 'dongtaijiazai/yy1/djxiao'; break;      //点击小声
            case 12: wz = 'dongtaijiazai/yy1/shibai'; break;     //失败
            case 8: wz = 'dongtaijiazai/yy1/keai'; break;        //可爱
            case 15: wz = 'dongtaijiazai/yy1/buda'; break;//boda
            case 24: wz = 'dongtaijiazai/yy1/xiu'; break;    //秀
            case 7: wz = 'dongtaijiazai/yy1/ding'; break;        //叮
            case 14: wz = 'dongtaijiazai/yy1/shengli'; break;    //胜利
            case 5: wz = 'dongtaijiazai/yy1/dianliu'; break;     //点击电流
            case 11: wz = 'dongtaijiazai/yy1/baozha'; break;     //爆炸
            case 4: wz = 'dongtaijiazai/yy1/djshixiao'; break;   //点击失效
            case 1: wz = 'dongtaijiazai/yy1/djkeai'; break;      //点击可爱
            case 16: wz = 'dongtaijiazai/yy1/duan'; break;    //duan
            case 28: wz = 'dongtaijiazai/yy1/pa'; break;    //麻将触碰
            case 29: wz = 'dongtaijiazai/yy1/peng'; break;    //p碰
            case 30: wz = 'dongtaijiazai/yy1/gang'; break;    //杠
            case 31: wz = 'dongtaijiazai/yy1/chi'; break;    //吃
            case 32: wz = 'dongtaijiazai/yy1/hule'; break;    //胡了
            case 33: wz = 'dongtaijiazai/yy1/bolinlin'; break;    //波零零
            case 34: wz = 'dongtaijiazai/yy1/daluan'; break;    //麻将
            case 13: wz = 'dongtaijiazai/yy1/jinbidiaoluo'; break;//金币掉落

            default: console.log('chucuole')
        };

        if (JSON.parse(localStorage.getItem('HC_yinxiaokongzhi'))) {
            this.bundle.load(wz, AudioClip, (er, au) => {
                if (er) {
                    console.log(er)
                } else {
                    if (this.yinpin) {
                        this.yinpin.playOneShot(au, daxiao)


                    }

                }
            })
        }

    }

    //动画
    doudongZXZ = []
    d抖动(nd: Node) {  //(nd：节点，0.3：时间，10：幅度)
        let fu = 10
        let shijian = 0.3
        if (this.doudongZXZ.indexOf(nd) == -1) {
            this.doudongZXZ.push(nd)
            tween(nd)
                .by(shijian / 8, { position: new Vec3(fu, fu, 0) })
                .by(shijian / 8, { position: new Vec3(- fu, - fu, 0) })
                .by(shijian / 8, { position: new Vec3(-fu, fu, 0) })
                .by(shijian / 8, { position: new Vec3(fu, - fu, 0) })
                .by(shijian / 8, { position: new Vec3(-fu, -fu, 0) })
                .by(shijian / 8, { position: new Vec3(fu, fu, 0) })
                .by(shijian / 8, { position: new Vec3(fu, -fu, 0) })
                .by(shijian / 8, { position: new Vec3(-fu, fu, 0) })
                .call(() => {
                    let dhs = this.doudongZXZ.indexOf(nd)
                    this.doudongZXZ.splice(dhs, 1)
                })
                .start()
        }
    }

    XZzhong = []
    x旋转(nd: Node) {  //(nd：节点，0.3：时间，10：幅度)
        if (this.XZzhong.indexOf(nd) == -1) {
            this.XZzhong.push(nd)
            tween(nd)
                .by(0.3, { angle: -6 })
                .by(0.3, { angle: 6 })
                .by(0.3, { angle: -6 })
                .by(0.3, { angle: 6 })
                .call(() => {
                    let dhs = this.XZzhong.indexOf(nd)
                    this.XZzhong.splice(dhs, 1)

                })
                .start()
        }
    }


    f反转(nd: Node, 时间?, 次数?) {
        if (this.XZzhong.indexOf(nd) == -1) {
            this.XZzhong.push(nd)

            let sj = 0.2
            let cs = 2

            if (时间) {
                sj = 时间
            }
            if (次数) {
                cs = 次数
            }

            let t = tween(nd).to(sj, { scale: v3(-1, 1, 1) }).to(sj, { scale: v3(1, 1, 1) })
            tween(nd).repeat(cs, t).call(() => {
                let dhs = this.XZzhong.indexOf(nd)
                this.XZzhong.splice(dhs, 1)
            })
                .start()
        }
    }

    j逐显(n: Node) {
        n.getComponent(UIOpacity).opacity = 0
        Tween.stopAllByTarget(n)
        tween(n.getComponent(UIOpacity)).to(0.3, { opacity: 255 }).delay(0.8).to(0.3, { opacity: 0 }).start()
    }

    j逐显2(n: Node, time: number, opa: number) {
        Tween.stopAllByTarget(n)
        tween(n.getComponent(UIOpacity)).to(time, { opacity: opa }).start()
    }

    c持续缩放(n: Node) {
        Tween.stopAllByTarget(n)
        let tw = tween(n).to(0.8, { scale: v3(0.9, 0.9, 0.9) }).to(0.8, { scale: v3(1, 1, 1) })
        tween(n).repeatForever(tw).start()
    }

    c持续闪烁(n: Node) {
        Tween.stopAllByTarget(n)
        n.getComponent(UIOpacity).opacity = 100
        let tw = tween(n.getComponent(UIOpacity)).to(0.3, { opacity: 100 }).to(0.3, { opacity: 255 })
        tween(n.getComponent(UIOpacity)).tag(99).repeatForever(tw).start()
    }

    t停止闪烁(n) {
        Tween.stopAllByTag(99, n.getComponent(UIOpacity))
        n.getComponent(UIOpacity).opacity = 255

    }


    c持续旋转(n: Node, j角度, s时间) {
        Tween.stopAllByTarget(n)
        n.angle = j角度
        let t = tween(n).to(s时间, { angle: -j角度 }).to(s时间, { angle: j角度 })
        tween(n).repeatForever(t).start()
    }

    d动态修改数值(d对象: { num: number }, n: Node, time, 最终数值) {
        let duixiang = d对象
        tween(duixiang).to(time, { num: 最终数值 }, {
            onUpdate: (targer, tim) => {
                let str = duixiang.num.toFixed(0)
                if (n) {
                    this.x修改文字(n, str)
                }

            }
        }).start()
    }

    //文字
    tszhong = []
    t提示(n: Node, v3: Vec3, wzn, lab) {
        if (this.XZzhong.indexOf(n) == -1) {
            wzn.getComponent(Label).string = lab

            this.XZzhong.push(n)
            let ts = n
            ts.setPosition(v3)
            ts.getComponent(UIOpacity).opacity = 0
            tween(ts.getComponent(UIOpacity)).to(0.2, { opacity: 255 }).delay(1.5).to(0.3, { opacity: 0 })
                .call(() => {
                    ts.setPosition(-1000, 45)
                    let dhs = this.XZzhong.indexOf(n)
                    this.XZzhong.splice(dhs, 1)

                })
                .start()
        }
    }

    t提示通用(str: string) {
        let t = find('Canvas/通用提示')
        if (!t) {
            let n = instantiate(this.TSnode)
            n.setParent(find('Canvas'))
        }
        let tns = this.find查找('Canvas/通用提示')

        let wzn = tns.getChildByName('Label')
        let wz = str
        this.x修改文字(wzn, wz)

        let f = () => {
            tns.setPosition(0, -20)
            let wznuiSZ = wzn.getComponent(UITransform).contentSize
            let fknui = tns.getChildByName('fangkuai').getComponent(UITransform)
            fknui.setContentSize(wznuiSZ.width + 30, wznuiSZ.height)

            this.x修改透明度(tns, 180)
            Tween.stopAllByTarget(tns.getComponent(UIOpacity))
            Tween.stopAllByTarget(tns)
            tween(tns.getComponent(UIOpacity)).to(0.2, { opacity: 255 }).delay(0.8).to(0.2, { opacity: 0 }).start()
            tween(tns).to(0.2, { position: v3(0, 0) }).delay(1).set({ position: v3(2000, 2000) }).start()
        }
        this.scheduleOnce(f, 0.01)
    }


    //功能

    find查找(a: string): Node {
        let n = find(a)
        if (n) {
            return n
        } else {
            console.log('路径错误：' + a)
        }
    }

    X修改子节点位置(n: Node, _1为最上显示0为最下) {
        if (_1为最上显示0为最下 == 1) {
            n.setSiblingIndex(n.parent.children.length + 1)
        } else {
            n.setSiblingIndex(0)
        }
    }

    x渲染顺序(n: Node, num) {
        n.getComponent(UITransform).priority = num
    }

    b播放粒子(n: Node) {
        n.getComponent(ParticleSystem2D).resetSystem()
    }

    L粒子当前是否播放(n: Node) {
        if (n.getComponent(ParticleSystem2D).particleCount == 0) {
            return false
        } else {
            return true
        }

    }

    y预加载场景(场景名: string, 分包名?: string) {
        let fb = 'fb'
        if (分包名) {
            fb = 分包名
        }
        assetManager.loadBundle(fb, (err, a) => { a.loadScene(场景名, (err, a) => { console.log(场景名 + '场景预加载完成') }) })
    }


    @property(Material) 内描边: Material = null;
    s设置描边(n: Node, 颜色: string, 描边大小?: number) {
        if (Material) {
            n.getComponent(Sprite).customMaterial = this.内描边
            let cz = n.getComponent(Sprite).customMaterial
            cz.setProperty('_OutlineColor', color().fromHEX('#EEA92E'))    //设置颜色
            if (描边大小) {
                cz.setProperty('_OutlineSize', 描边大小)   //设置描边大小
            } else {
                cz.setProperty('_OutlineSize', 15)
            }

        } else {
            console.log('没有添加描边材质')
        }

    }

    q取消描边(n: Node) {
        n.getComponent(Sprite).customMaterial = null
    }


    //数据数组

    Rand = (a, b) => { return Math.floor(Math.random() * (b - a + 1)) + a }

    Rand21 = (a, b) => {
        if (this.Rand(0, 1) == 0) {
            return a
        } else {
            return b
        }
    }

    s随机打乱(arr) { arr.sort(() => { return Math.random() > 0.5 ? -1 : 1 }) }

    p判断距离(WZ1: Vec3 | Vec2, WZ2: Vec3 | Vec2, JL: number) { //小于距离返还true
        if (Math.abs(Math.round(Math.sqrt((WZ1.x - WZ2.x) * (WZ1.x - WZ2.x) + (WZ1.y - WZ2.y) * (WZ1.y - WZ2.y)))) <= JL) { return true; } else { return false }
    }


    j夹角计算(v1: Vec2 | Vec3, v2: Vec2 | Vec3): number {
        let x1 = v1.x
        let x2 = v2.x
        let y1 = v1.y
        let y2 = v2.y
        // 计算两个点之间的向量
        const deltaX = x2 - x1;
        const deltaY = y2 - y1;

        // 计算向量的长度
        const length = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

        // 如果长度为0，说明两个点重合，夹角为0
        if (length === 0) {
            return 0;
        }

        // 使用点积公式计算夹角
        // 这里我们计算的是向量(1,0)与(deltaX, deltaY)之间的夹角
        // 因为(1,0)是X轴的单位向量，所以这个夹角就是我们要找的与X轴的夹角
        const dotProduct = 1 * deltaX + 0 * deltaY;
        const angleRadians = Math.acos(dotProduct / length);

        // 将弧度转换为角度
        const angleDegrees = angleRadians * (180 / Math.PI);

        return angleDegrees;
    }


    p判断连续的数字位置(lst: number[]): { numbers: [number, number, number][], w位置: [number, number, number][] } {
        let numbers: [number, number, number][] = [];
        let positions: [number, number, number][] = [];

        for (let i = 0; i < lst.length; i++) {
            // 寻找递增序列
            let a = lst[i];
            let bFound = false;
            let cFound = false;
            let bIndex = -1;
            let cIndex = -1;
            for (let j = i + 1; j < lst.length; j++) {
                if (lst[j] === a + 1) {
                    bFound = true;
                    bIndex = j;
                    a = lst[j];
                    break;
                }
            }
            if (bFound) {
                for (let k = bIndex + 1; k < lst.length; k++) {
                    if (lst[k] === a + 1) {
                        cFound = true;
                        cIndex = k;
                        break;
                    }
                }
            }
            if (bFound && cFound) {
                numbers.push([lst[i], lst[bIndex], lst[cIndex]]);
                positions.push([i, bIndex, cIndex]);
            }
        }

        return { numbers, w位置: positions };
    }

    s数组排序(_1为升序2为降序, sz: any[]) {
        if (_1为升序2为降序 == 1) {
            sz.sort((a, b) => a - b)
            return sz
        } else {
            sz.sort((a, b) => b - a)
            return sz
        }
    }

    s节点数组按名字排序(_1为升序2为降序, sz: Node[]) {
        if (_1为升序2为降序 == 1) {
            sz.sort((a, b) => JSON.parse(a.name) - JSON.parse(b.name))
            return sz
        } else {
            sz.sort((a, b) => JSON.parse(a.name) - JSON.parse(b.name))
            return sz
        }
    }

    s节点数组按属性排序(_1为升序2为降序, sz: Node[]) {
        if (_1为升序2为降序 == 1) {

            sz.sort((a, b) => JSON.parse(a.name) - JSON.parse(b.name))
            return sz
        } else {
            sz.sort((a, b) => JSON.parse(a.name) - JSON.parse(b.name))
            return sz
        }
    }

    //格式

    z转行列号(代号, 总列数) {
        let hlh = {
            h: 0,
            l: 0,
        }
        let shuzhi = 0
        let hanghao = 0
        let liehao = 0
        for (let i = 0; i < 代号; i++) {
            liehao++
            if (liehao == 总列数) {
                liehao = 0
                hanghao++
            }
            shuzhi++
        }
        hlh.h = hanghao
        hlh.l = liehao
        return hlh
    }

    z转代号(hh, lh, z总列数) {
        let num = lh + hh * z总列数
        return num
    }

    s设置位置(nod: Node, 列号, 行号, 初始x, 初始y, 间隔距离x, 间隔距离y) {
        let x = 初始x + 列号 * 间隔距离x
        let y = 初始y + 行号 * 间隔距离y
        nod.setPosition(x, y)

    }

    s设置世界位置(nod: Node, 列号, 行号, 初始x, 初始y, 间隔距离x, 间隔距离y) {
        let x = 初始x + 列号 * 间隔距离x
        let y = 初始y + 行号 * 间隔距离y
        nod.setWorldPosition(x, y, 0)
    }

    //修改属性
    x修改文字(node: Node, str: string) {
        if (!node) {
            console.log('没有找找到节点')
        }
        node.getComponent(Label).string = str
    }

    x修改颜色(node: Node, HEX: string) {
        node.getComponent(Sprite).color = color().fromHEX(HEX)
    }

    x修改透明度(node: Node, num: number) {
        let op = node.getComponent(UIOpacity)
        if (op) {
            op.opacity = num
        } else (
            console.log('找不到透明主键' + node)
        )

    }

    x修改Button参数(n: Node, c参数: string) {
        const button = n.getComponent(Button);
        button.clickEvents[0].customEventData = c参数
    }


    //ui通用
    t弹出通用(n: Node) {
        n.setPosition(0, 0)
        let nz = n.getChildByName('小组')
        nz.setScale(0.1, 0.1, 1)
        tween(nz).to(0.3, { scale: v3(1, 1, 1) }).start()
    }

    g关闭通用(n: Node) {
        n.setPosition(2000, 5000)
    }

    b倍率 = 1
    奖励金币b倍率动画(基础金币数: number, 基础文字: Node, 多倍文字: Node, 移动装饰: Node) {
        let jbs = 基础金币数
        this.x修改文字(基础文字, 'x' + jbs)

        let shaizi = 移动装饰
        Tween.stopAllByTarget(shaizi)
        shaizi.setPosition(-200, 40)
        let t = tween(shaizi).to(0.6, { position: v3(200, 40) }).to(0.6, { position: v3(-200, 40) })
        tween(shaizi).repeatForever(t).start()
        let dnz = 多倍文字
        let f = () => {
            this.x修改文字(dnz, "x" + jbs * this.b倍率)
        }
        let t2 = tween(dnz)
            .call(() => {
                this.b倍率 = 2
                f()
            })
            .delay(0.1)
            .call(() => {
                this.b倍率 = 3
                f()
            })
            .delay(0.1)
            .call(() => {
                this.b倍率 = 4
                f()
            })
            .delay(0.1)
            .call(() => {
                this.b倍率 = 5
                f()
            })
            .delay(0.1)
            .call(() => {
                this.b倍率 = 4
                f()
            })
            .delay(0.1)
            .call(() => {
                this.b倍率 = 3
                f()
            })
            .delay(0.1)
            .call(() => {
                this.b倍率 = 2
                f()
            })

        Tween.stopAllByTarget(dnz)
        tween(dnz).repeatForever(t2).start()
    }

    d点击移动位置(e: EventTouch) {
        let v2 = new Vec2
        e.getUILocation(v2)
        let v3 = new Vec3(v2.x, v2.y, 0)
        let v = new Vec3(0, 0, 0)
        find('Canvas').getComponent(UITransform).convertToNodeSpaceAR(v3, v)     //转换坐标
        return v
    }


    //其他小程序api

    z震动执行() {
        if (JSON.parse(localStorage.getItem('HC_yinxiaokongzhi'))) {
            console.log('震动')
            weixinapi.z微信震动()
        }
    }

    c创建插屏() {
        if (SJTS.q其他广告开启) {
            weixinapi.c展示插屏广告()
        }
    }

    c创建banner(_1格子2banner) {
        if (SJTS.q其他广告开启) {
            weixinapi.z展示banner广告()

            /* 
            let f=()=>{
                this.g关闭banner()
            }
            this.c常驻定时器(this.banner最长停留时间,f)
             */
        }

    }

    async c创建激励广告(f) {
        let adUnitId = TaskProxy.inst.taskConfig.m_CommmonRewardID;
        if (!adUnitId) {
            console.error('未获取到广告id');
            return;
        }
        let ad = Guyu.AdFactory.getAD({ adUnitId: adUnitId, init: true });
        let { success, errMsg } = await ad.playAd({
            showError: true,
            showLoading: true,
        });
        if (!success) {
            CommonUI.showToast(errMsg);
            return;
        }
        f();
        return;
        weixinapi.z展示激励广告(f)
    }

    g关闭banner() {
        if (SJTS.q其他广告开启) {
            weixinapi.g关闭banner()
            weixinapi.g关闭格子()
        }
    }

    f分享(f) {
        let fsb = () => {
            this.bofangshenyin(4)
            this.t提示通用('分享失败')
        }

        weixinapi.starttime = new Date().getTime();
        weixinapi.F_fxcg = f
        weixinapi.F_fxsb = fsb
        weixinapi.onshowzx()

        weixinapi.f分享()

    }

    c常驻定时器(时间, 回调) {
        let cznd = new Node('changzhuzhixin');
        cznd.setParent(this.node.parent);
        cznd.setPosition(2000, 2000);
        director.addPersistRootNode(cznd)
        cznd.addComponent('CZdingshiqiTS')
        cznd.getComponent(CZdingshiqiTS).d定时 = 时间
        cznd.getComponent(CZdingshiqiTS).z执行函数 = 回调
        cznd.getComponent(CZdingshiqiTS).d定时开始 = true
    }

}